import jwt
from flask import current_app
from datetime import datetime,timedelta

# 生成token
def generate_token(payload,expiry,algorithm='HS256'):
    key = current_app.config.get('SECRET_KEY')
    if 'exp' not in payload:
        payload['exp'] = expiry
    try:
        token = jwt.encode(payload,key,algorithm)
        return token
    except Exception as e:
        print('生成token错误',e)
        return str(e)



# 效验token
def check_token(token):
    key = current_app.config.get('SECRET_KEY')

    payloay = jwt.decode(token,key,algorithms=['HS256'])
    return payloay



# 刷新token
def _generate_token(payload,is_refresh=True):
    # 设置有效期, 第一默认生成2个小时的有效期
    expiry = datetime.utcnow() + timedelta(hours=2)
    token = 'JWT ' + generate_token(payload,expiry)

    # 默认需要刷新生成token
    if is_refresh:
        # 生成一个15天的token
        expiry =datetime.utcnow() + timedelta(days=15)
        # 给payload 添加刷新token的标识
        # payload['is_refresh'] = True
        payload.update({'is_refresh':True})
        refresh_token = 'JWT ' + generate_token(payload,expiry)
    else:
        refresh_token = None
    return token,refresh_token




